package com.cat.twoPointerTechnique;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/push-dominoes/
 * @create 2025/8/9 15:28
 * @since JDK17
 */

public class Solution30 {
    public String pushDominoes(String dominoes) {
        StringBuilder ans = new StringBuilder(dominoes);
        int i = 0, j = 0, n = dominoes.length(), last = 0, l, r;
        while (j < n && dominoes.charAt(j) == '.') {
            j++;
        }
        if (dominoes.charAt(j) == 'L') {    // 左边的都得往右边倒
            while (i < j) {
                ans.setCharAt(i++, 'L');
            }
        }
        while (j < n) {
            // i是上一个不是'.'的位置
            while (j < n && dominoes.charAt(j) == '.') {
                j++;
            }
            char a = dominoes.charAt(i), b = dominoes.charAt(j);
            for (l = i + 1, r = j - 1; l < r; ) {
                if (a == 'R') {
                    ans.setCharAt(l++, 'R');
                }
                if (b == 'L') {
                    ans.setCharAt(r--, 'L');
                }
            }
            if (l == r && a == 'R' && b == 'L') {   //
                ans.setCharAt(l, '.');
            }
            i = j++;
        }

        return dominoes;
    }
}
